package com.shouer.doc.common.util;

import android.content.res.AssetManager;
import android.text.TextUtils;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by apple on 15/8/4.
 */
public class FileUtil {

    private static final String FILE_SEPARATOR = File.separator;

    public static String connectFilePath(String front, String rear) {
        // TODO Auto-generated method stub
        String result = "";
        if (!TextUtils.isEmpty(front) && !TextUtils.isEmpty(rear)) {
            if (front.endsWith(FILE_SEPARATOR)) {
                if (rear.startsWith(FILE_SEPARATOR)) {
                    result = front + rear.substring(1);
                } else {
                    result = front + rear;
                }
            } else {
                if (rear.startsWith(FILE_SEPARATOR)) {
                    result = front + rear;
                } else {
                    result = front + FILE_SEPARATOR + rear;
                }
            }
        }
        return result;
    }

    public static void copyAssetFileToSd(AssetManager assetManager, String assetFilePath, String sdFilePath) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = assetManager.open(assetFilePath);
            out = new FileOutputStream(sdFilePath);
            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
        } catch (Exception e) {
            Log.e("copyFile", e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                    in = null;
                }
                if (out != null) {
                    out.flush();
                    out.close();
                    out = null;
                }
            } catch (IOException e) {
                Log.e(FileUtil.class.getSimpleName(),e.toString());
            }

        }
    }

    public static void copyAssetFile(AssetManager assetManager, String assetFilePath, String desFilePath) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = assetManager.open(assetFilePath);
            out = new FileOutputStream(desFilePath);
            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
        } catch (Exception e) {
            Log.e("copyFile", e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                    in = null;
                }
                if (out != null) {
                    out.flush();
                    out.close();
                    out = null;
                }
            } catch (IOException e) {
                Log.e(FileUtil.class.getSimpleName(),e.toString());
            }

        }
    }

    public static boolean deleteDirectory(String filePath) {
        boolean flag = false;
        //如果filePath不以文件分隔符结尾，自动添加文件分隔符
        if (!filePath.endsWith(File.separator)) {
            filePath = filePath + File.separator;
        }
        File dirFile = new File(filePath);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        flag = true;
        File[] files = dirFile.listFiles();
        //遍历删除文件夹下的所有文件(包括子目录)
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                //删除子文件
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } else {
                //删除子目录
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前空目录
        return dirFile.delete();
    }


    public static boolean deleteChildFiles(String filePath) {
        boolean flag = false;
        //如果filePath不以文件分隔符结尾，自动添加文件分隔符
        if (!filePath.endsWith(File.separator)) {
            filePath = filePath + File.separator;
        }
        File dirFile = new File(filePath);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        flag = true;
        File[] files = dirFile.listFiles();
        //遍历删除文件夹下的所有文件(包括子目录)
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                //删除子文件
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } else {
                //删除子目录
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前空目录
        return true;
    }

    /**
     * 删除单个文件
     *
     * @param filePath 被删除文件的文件名
     * @return 文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            return file.delete();
        }
        return false;
    }

    /**
     * 输入流转byte[]
     *
     * @param inStream InputStream
     * @return Byte数组
     */
    public static final byte[] input2byte(InputStream inStream) {
        if (inStream == null)
            return null;
        byte[] results = new byte[0];
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        try {
            while ((rc = inStream.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            results = swapStream.toByteArray();
        } catch (IOException e) {
            Log.e(FileUtil.class.getSimpleName(),e.toString());
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                inStream = null;
            }

            if (null != swapStream) {
                try {
                    swapStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                swapStream = null;
            }
        }
        return results;
    }

    public static boolean isFileExists(String fileDirPath, String fileName) {
        File file = new File(fileDirPath, fileName);

        return file.exists();
    }

    public static long FileFolder_Used_Size(File pathFile) {

        android.os.StatFs statfs = new android.os.StatFs(pathFile.getPath());
        long nTotalBlocks = statfs.getBlockCount();            // 获取SDCard上BLOCK总数
        long nBlocSize = statfs.getBlockSize();                   // 获取SDCard上每个block的SIZE
        long nAvailaBlock = statfs.getAvailableBlocks();          // 获取可供程序使用的Block的数量
        long nSDUsedSize = (nTotalBlocks - nAvailaBlock) * nBlocSize / 1024;
        return nSDUsedSize;
    }

    public static String getFileName(String filePath)
    {
        return filePath.substring(filePath.lastIndexOf(File.separator));
    }

    public static byte[] getBytes(String filePath) {
        byte[] buffer = null;
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        try {
            File file = new File(filePath);
            fis = new FileInputStream(file);
            bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }

            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fis) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != bos) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer;
    }

}
